package com.zxc.gulimall.auth.web;

import com.alibaba.fastjson.TypeReference;
import com.zxc.common.utils.R;
import com.zxc.gulimall.auth.vo.UserRegisterVo;
import com.zxc.gulimall.auth.feign.MemberFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class RegController {

    @Autowired
    private MemberFeignService memberFeignService;

    /*
     * RedirectAttributes 模拟重定向携带数据,session里面的数据用过一次就会删掉
     * */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if (result.hasErrors()){
            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",collect);
            //校验出错，转发到注册页

            //Request method 'POST' not supported ===> forward是在原有的请求的基础上进行转发，我们路径映射的是get请求到reg.html，但是注册方法的请求方式是Post，导致了这个错误
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //TODO-验证码服务  校验验证码 + redis存储 验证码_手机号
        //开始注册；调用远程member-service服务
        R register = memberFeignService.register(vo);
        if (register.getCode() == 0){
            //注册成功回到首页/登录页
            return "redirect:http://auth.gulimall.com/login.html";
        }else {
            //注册失败
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",register.getData(new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

    }

}
